package de.hauschild.jchronology;

import java.util.Date;

import javax.management.timer.Timer;

public class Duration {

  private long duration;

  public Duration() {
    this(0);
  }

  public Duration(final Date theBegin, final Date theEnd) {
    this(theEnd.getTime() - theBegin.getTime());
  }

  public Duration(final long theDuration) {
    duration = theDuration;
  }

  public Duration(final String theString) {
    final String[] splitted = theString.split(":");
    if (splitted.length != 2) {
      throw new IllegalArgumentException("The given string has not form '##:##': " + theString);
    }
    try {
      final int hours = Integer.parseInt(splitted[0].trim());
      final int minutes = Integer.parseInt(splitted[1].trim());
      duration = hours * Timer.ONE_HOUR + minutes * Timer.ONE_MINUTE;
    } catch (final NumberFormatException ex) {
      throw new IllegalArgumentException("Unable to parse the duration: " + theString);
    }
  }

  public void add(final Duration theDuration) {
    if (theDuration == null) {
      return;
    }
    duration += theDuration.getDuration();
  }

  public long getDuration() {
    return duration;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString() {
    final int hours = (int) (duration / Timer.ONE_HOUR);
    final int minutes = (int) ((duration - hours * Timer.ONE_HOUR) / Timer.ONE_MINUTE);
    final StringBuilder builder = new StringBuilder();
    if (duration < 0) {
      builder.append("-");
    }
    builder.append(String.format("%02d:%02d", Math.abs(hours), Math.abs(minutes)));
    return builder.toString();
  }

}
